package com.mxpio.erp.purchase.controller;


import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import com.mxpio.erp.purchase.policy.impl.RejectNoticePolicy;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.mxpio.erp.common.enums.NoticeStatusEnums;
import com.mxpio.erp.common.enums.OrderEnums;
import com.mxpio.erp.common.jpa.model.Notice;
import com.mxpio.erp.common.order.policy.NoticeContext;
import com.mxpio.erp.common.order.service.NoticeService;
import com.mxpio.erp.common.purchase.entity.RejectNotice;
import com.mxpio.erp.common.purchase.entity.RejectNoticeLine;
import com.mxpio.erp.common.purchase.service.RejectNoticeService;
import com.mxpio.erp.common.technology.entity.Item;
import com.mxpio.erp.common.technology.service.ItemService;
import com.mxpio.erp.common.vo.OrderExcuteVo;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.policy.CrudContext;
import com.mxpioframework.jpa.policy.impl.CrudType;
import com.mxpioframework.jpa.policy.impl.SmartCrudPolicyAdapter;
import com.mxpioframework.jpa.query.Criteria;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;

@Tag(name = "RejectNoticeController", description = "采购退货通知单接口")
@RestController
@RequestMapping("/erp/purc/rj/")
public class RejectNoticeController {

    @Autowired
    private RejectNoticeService service;

    @Autowired
    private NoticeService noticeService;

    @Autowired
    private ItemService itemService;
    @GetMapping("list")
    @Operation(summary = "退货通知单列表", description = "获取退货通知单列表（无分页）", method = "GET")
    public Result<List<RejectNotice>> list(@Parameter(description="查询参数") Criteria criteria) throws UnsupportedEncodingException {
        List<RejectNotice> noticeList = service.list(RejectNotice.class, criteria);
        return Result.OK(noticeList);
    }

    @GetMapping("page")
    @Operation(summary = "退货通知单列表", description = "获取退货通知单列表（分页）", method = "GET")
    public Result<Page<RejectNotice>> page(@Parameter(description="查询参数") Criteria criteria, @Parameter(description="每页条数")Integer pageSize, @Parameter(description="页号")Integer pageNo) throws UnsupportedEncodingException {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Page<RejectNotice> noticeList = service.listPage(RejectNotice.class, page, criteria);
        return Result.OK(noticeList);
    }

    @GetMapping("list/{noticeNo}")
    @Operation(summary = "根据noticeNo获取退货通知单", description = "根据noticeNo获取退货通知单", method = "GET")
    public Result<RejectNotice> getById(@Parameter(description="通知单号") @PathVariable(name = "noticeNo", required = true) String noticeNo) {
        RejectNotice noticeList = service.getById(RejectNotice.class, noticeNo);
        return Result.OK(noticeList);
    }

    @PostMapping("add")
    @Operation(summary = "新增退货通知单", description = "新增退货通知单", method = "POST")
    public Result<RejectNotice> add(@RequestBody RejectNotice notice) {
        service.save(notice);
        return Result.OK(notice);
    }

    @RequestMapping("save")
    @Operation(summary = "保存采购退货通知单", description = "保存采购退货通知单")
    public Result<RejectNotice> save(@RequestBody RejectNotice notice) {
        if (CrudType.SAVE.equals(notice.getCrudType())){
            notice.setNoticeDate(new Date());
            notice.setAccessType(OrderEnums.AccessType.OUT.getCode());
            notice.setPickingType(NoticeStatusEnums.NoticeType.PO_OUT.getCode());//采购退货
            notice.setNoticeStatus(NoticeStatusEnums.NoticeStatus.CREATE.getStatusCode());
            List<RejectNoticeLine> rejectBillLines = notice.getRejectBillLines();
            for(RejectNoticeLine line : rejectBillLines) {
                Item item = itemService.getById(Item.class,line.getItemCode());
                line.setItemName(item.getItemName());
                line.setItemSpec(item.getItemSpec());
                line.setUnitCode(item.getUnitCode());
            }
        }else{
            List<RejectNoticeLine> rejectBillLines = notice.getRejectBillLines();
            for(RejectNoticeLine line : rejectBillLines) {
                if (CrudType.SAVE.equals(line.getCrudType())){
                    Item item = itemService.getById(Item.class,line.getItemCode());
                    line.setItemName(item.getItemName());
                    line.setItemSpec(item.getItemSpec());
                    line.setUnitCode(item.getUnitCode());
                }
            }
        }

        service.save(notice,new SmartCrudPolicyAdapter(){
            @Override
            public boolean beforeInsert(CrudContext context) {
                Object o = context.getEntity();
                if(o instanceof RejectNoticeLine){
                    RejectNotice rejectNotice = context.getParent();
                    ((RejectNoticeLine) o).setNoticeNo(rejectNotice.getNoticeNo());
                }
                return true;
            }
        });
        return Result.OK(notice);
    }

    @PutMapping("edit")
    @Operation(summary = "编辑退货通知单", description = "编辑退货通知单", method = "PUT")
    public Result<RejectNotice> edit(@RequestBody RejectNotice notice) {
        service.update(notice);
        return Result.OK(notice);
    }

    @DeleteMapping("remove/{noticeNos}")
    @Operation(summary = "根据noticeNo删除退货通知单", description = "删除退货通知单", method = "DELETE")
    public Result<RejectNotice> remove(@Parameter(description="业务单号，多个单号用英文逗号分隔") @PathVariable(name = "noticeNos", required = true) String noticeNos) {
        String[] noticeNo = noticeNos.split(",");
        for(String key : noticeNo){
            service.delete(RejectNotice.class, key);
        }
        return Result.OK();
    }

    @RequestMapping("execute/{noticeNo}")
    @Operation(summary = "通知单执行", description = "通知单执行")
    public Result<Object> excute(@PathVariable(name = "noticeNo", required = true) String noticeNo,
                                 @RequestBody OrderExcuteVo orderExcuteVo) {
        RejectNotice notice = service.getById(RejectNotice.class, noticeNo);
        if (notice.getNoticeStatus().equals(NoticeStatusEnums.NoticeStatus.CONFIRM.getStatusCode())){
            return Result.error("单据状态已发生变化，已确认状态单据不允许重复确认！");
        }
        NoticeContext context = noticeService.execute(notice, new RejectNoticePolicy(orderExcuteVo.getLines()));
        if(CollectionUtils.isEmpty(context.getErrors())) {
            return Result.OK();
        }else {
            return Result.error(context.getErrors().get(0));
        }
    }

    @PutMapping("reject/{noticeNo}")
    @Operation(summary = "拒绝通知单", description = "拒绝通知单", method = "PUT")
    public Result<? extends Notice> close(@Parameter(description="通知单号") @PathVariable(name = "noticeNo", required = true) String noticeNo) {
        RejectNotice notice = service.getById(RejectNotice.class,noticeNo);
    	return noticeService.updateNoticeStatus(notice, NoticeStatusEnums.NoticeStatus.REJECT);
    }

    @GetMapping("listbynos/{noticeNos}")
    @Operation(summary = "根据noticeNos获取对应采购退货通知单及明细", description = "根据noticeNos获取采购退货通知单及明细", method = "GET")
    public Result<List<RejectNotice>> getByIds(@PathVariable(name = "noticeNos", required = true) String noticeNos) {
        return service.listByIds(noticeNos);
    }
}
